﻿/*
Copyright (c) Microsoft Corporation

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.  You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0   

THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.  

See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. 
*/

(function () {

    WinJS.UI.processAll();

    WinJS.UI.Pages.define("/hiker.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            var state = WinJS.Navigation.state;
            if (typeof (state.data.isTemplate) == 'undefined' || !state.data.isTemplate) {
                var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
                dataTransferManager.addEventListener('datarequested', shareHikerHandler);
            };

            var picker = Windows.ApplicationModel.Contacts.ContactPicker();
            picker.commitButtonText = "Select";

            var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
            openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
            openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
            openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
            openPicker.commitButtonText = "Select";

            var thumbURL = null;

            var colorFlyout = document.getElementById('colorFlyout');
            var imageMenu = document.getElementById('imageMenu');
            var nameFlyout = document.getElementById('nameFlyout');
            var nameTextInput = document.getElementById('name');
            var picConfButton = document.getElementById('pic_conf');
            var shareButton = document.getElementById('share');
            var nameSaveButton = document.getElementById('name_save_button');
            var selectFromContactsOption = document.getElementById('fromcontacts');
            var selectFromFileOption = document.getElementById('fromfile');
            var preview_box = document.getElementById('edit_img_wrap');
            var control_boxes = document.getElementsByClassName('edit_control_box');

            WinJS.Utilities.query("a").listen("click", linkClickEventHandler, false);
            var templ = document.getElementById('edit_temp');
            WinJS.Binding.processAll(templ, state.data);



            // show color flyout
            document.getElementById('color_conf').addEventListener('click', function (ev) {
                colorFlyout.winControl.show(this, 'top', 'left');
            }, false);

            // show name flyout
            document.getElementById('name_conf').addEventListener('click', function (ev) {
                document.getElementById('name').value = WinJS.Navigation.state.data.title;
                nameFlyout.winControl.show(this, 'top','right');
            }, false);

            var color_options = WinJS.Utilities.query('.color_option');

            for (var i = 0; i < color_options.length; i++) {
                // change color when color option changed
                color_options[i].addEventListener('click', function (evt) {
                    var elm = evt.target;
                    var state = WinJS.Navigation.state;
                    var data = state.data;
                    var index = parseInt(state.key);
                    var value = elm.getAttribute('data-value');
                    var color_frame = elm.getAttribute('data-color-frame');
                    // create new hiker if this is from a new hiker template
                    if (typeof (data.isTemplate) != 'undefined' && data.isTemplate) {
                        data = makeNewHiker();
                        data.frame = parseInt(color_frame);
                        data.color = '#%'.replace('%', value);
                        data.picture = 'images/climber_%_big.png'.replace('%', value);
                        data.isTemplate = false;
                        var l = DataHikers.itemList.push(data);
                        index = (l - 1); /*correct for zero based index*/
                    } else {
                        data.frame = parseInt(color_frame);
                        data.color = '#%'.replace('%', value);
                        data.picture = 'images/climber_%_big.png'.replace('%', value);
                    }
                    colorFlyout.winControl.hide();

                    
                    var face_img = new Image();
                    var body_img = new Image();

                    body_img.onload = (function () {
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');

                        //start compos
                        canvas.height = this.height;
                        canvas.width = this.width;
                        ctx.drawImage(face_img, 53, 68, 105, 105);
                        ctx.drawImage(this, 0, 0);
                        var compos_data_url = canvas.toDataURL();
                        data.compos_data_url = compos_data_url;

                        DataHikers.itemList.setAt(index, data);
                        // reload screen with new data
                        WinJS.Navigation.navigate('/hiker.html', { key: index, data: DataHikers.itemList.getAt(index) });
                    });

                    face_img.onload = (function () {// save new image data to hiker
                        body_img.src = state.data.picture;
                    });

                    face_img.src = state.data.profile_pic;

                    // reload screen with new state data
                    //WinJS.Navigation.navigate('/hiker.html', {key: index, data: DataHikers.itemList.getAt(index)});
                });
            };

            // show pic config control
            picConfButton.addEventListener('click', function (ev) {
                imageMenu.winControl.show(this, 'top', 'left');
            });

            // select from contacts selected
            selectFromContactsOption.addEventListener('click', function (ev) {
                var thumb = picker.pickSingleContactAsync().then(function (contact) {
                    if(!contact){
                        return false;
                    };

                    var face_img = new Image();
                    var body_img = new Image();

                    body_img.onload = (function () {
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        var dataurl = returnDataUrlFromImg(face_img);

                        var state = WinJS.Navigation.state;
                        var data = state.data;
                        var index = parseInt(state.key);
                        // save image data to hiker data object
                        var save_result = saveProfilePic(data, dataurl);
                        data = save_result.data;
                        index = (save_result.index ? save_result.index : index);
                        imageMenu.winControl.hide();

                        //start composite
                        canvas.height = this.height;
                        canvas.width = this.width;
                        ctx.drawImage(face_img, 53, 68, 105, 105);
                        ctx.drawImage(this, 0, 0);
                        var compos_data_url = canvas.toDataURL();
                        data.compos_data_url = compos_data_url;

                        DataHikers.itemList.setAt(index, data);

                        // reload screen with new data
                        WinJS.Navigation.navigate('/hiker.html', { key: index, data: DataHikers.itemList.getAt(index) });
                    });

                    face_img.onload = (function () {// save new image data to hiker
                        body_img.src = state.data.picture;
                    });

                    // get thumbnail
                    return contact.getThumbnailAsync().done(function (thumbnail) {
                        if (thumbnail) {
                            thumbURL = URL.createObjectURL(thumbnail, { oneTimeOnly: true });
                            face_img.src = thumbURL;
                        }
                    });

                });

            });

            // select from file option selected
            selectFromFileOption.addEventListener('click', function (ev) {
                var face_img = new Image();
                var body_img = new Image();

                body_img.onload = function () {// save new image data to hiker
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    var state = WinJS.Navigation.state;
                    var data = state.data;
                    var index = parseInt(state.key);

                    var dataurl = returnDataUrlFromImg(face_img);
                    // save image data to hiker data object

                    var save_result = saveProfilePic(data, dataurl);
                    data = save_result.data;
                    index = (save_result.index ? save_result.index : index);
                    imageMenu.winControl.hide();

                    //start composite
                    canvas.height = this.height;
                    canvas.width = this.width;
                    ctx.drawImage(face_img, 53, 68, 105, 105);
                    ctx.drawImage(this, 0, 0);
                    var compos_data_url = canvas.toDataURL();
                    data.compos_data_url = compos_data_url;

                    DataHikers.itemList.setAt(index, data);
                    // reload screen with new data
                    WinJS.Navigation.navigate('/hiker.html', { key: index, data: DataHikers.itemList.getAt(index) });
                };

                face_img.onload = (function () {// save new image data to hiker
                    body_img.src = state.data.picture;
                });
                openPicker.pickSingleFileAsync().then(function (file) {
                    if (file) {
                        var url = URL.createObjectURL(file, { oneTimeOnly: true });
                        face_img.src = url;
                    };
                });

            });

            nameSaveButton.addEventListener('click', function (ev) {
                var new_name = nameTextInput.value;
                var state = WinJS.Navigation.state;
                var data = state.data;
                var index = parseInt(state.key);

                if (typeof (data.isTemplate) != 'undefined' && data.isTemplate) {
                    data = makeNewHiker();
                    data.title = new_name;
                    data.isTemplate = false;
                    var l = DataHikers.itemList.push(data);
                    index = (l - 1); /*correct for zero based index*/
                } else {
                    data.title = new_name;
                    DataHikers.itemList.setAt(index, data);
                };

                nameFlyout.winControl.hide();
                WinJS.Navigation.navigate('/hiker.html', { key: index, data: DataHikers.itemList.getAt(index) });
            });

            shareButton.addEventListener('click', function (ev) {
                Windows.ApplicationModel.DataTransfer.DataTransferManager.showShareUI();
            })

        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />
            /// <param name="viewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
            /// <param name="lastViewState" value="Windows.UI.ViewManagement.ApplicationViewState" />

            // TODO: Respond to changes in viewState.
        },

        unload: function () {
            var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
            dataTransferManager.removeEventListener('datarequested', shareHikerHandler);
        }
    });

    function saveProfilePic(data, dataurl) {
        var index = null;
        if (typeof (data.isTemplate) != 'undefined' && data.isTemplate) {
            data = makeNewHiker();
            data.profile_pic = dataurl;
            data.isTemplate = false;
            var l = DataHikers.itemList.push(data);
            index = (l - 1);// correct for zero based index
        } else {
            data.profile_pic = dataurl;
        }

        return { data: data, index: index };
    };

    function shareHikerHandler(e) {
        var request = e.request;
        var state = WinJS.Navigation.state;
        var def = request.getDeferral();
        var id = state.data.id;
        try {
            var appData = Windows.Storage.ApplicationData.current; 
            var localFolder = appData.localFolder;
            var localMap = "img.png"; 

            request.data.properties.title = 'Check out the hiker character I made!';
            request.data.properties.description = "Share this hiker with a friend";

            var temp_img = new Image();
            var img_path = state.data.compos_data_url;
            temp_img.onload = (function () {
                var blob = returnBlobFromImg(this);

                Windows.Storage.ApplicationData.current.localFolder.createFileAsync("#_compos.png".replace('#', id), Windows.Storage.CreationCollisionOption.replaceExisting)
                .then(function (file) {
                    // create stream
                    return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
                })
                .then(function (stream) {
                    outputStream = stream;
                    out = stream.getOutputStreamAt(0);
                    blobStream = blob.msDetachStream();
                    return Windows.Storage.Streams.RandomAccessStream.copyAsync(blobStream, out);
                })
                .then(function () {
                    return out.flushAsync();
                }).done(function () {
                    blobStream.close();
                    out.close();
                    outputStream.close();
                    var html = "<img src='%'>".replace('%', localMap);
                    var htmlFormat = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.createHtmlFormat(html);
                    request.data.setHtmlFormat(htmlFormat);
                    var streamRef = Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(new Windows.Foundation.Uri("ms-appdata:///local/#_compos.png".replace('#', id)));
                    request.data.resourceMap[localMap] = streamRef;
                    def.complete();
                });
            });//end img on load
            temp_img.src = img_path;
        } 
        catch (ex) { 
            console.log(ex);
        } 


    };

})()